package com.kaibes.web.json;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;

@Configuration
public class JsonConfig {

	private List<String> xssIgnoreList = new ArrayList<>();
    {
        xssIgnoreList.add("predicate");
        xssIgnoreList.add("handler");
        xssIgnoreList.add("className");
        xssIgnoreList.add("descriptor");
        xssIgnoreList.add("mediaType");
        xssIgnoreList.add("origin");
        xssIgnoreList.add("value");
        xssIgnoreList.add("resource");
        xssIgnoreList.add("scope");
        xssIgnoreList.add("type");
        xssIgnoreList.add("name");
    }
    public void addXssIgnore(String name) {
        if (!xssIgnoreList.contains(name)) {
            xssIgnoreList.add(name);
        }
    }

	@Bean
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        SimpleModule module = new SimpleModule();
        
        XssStdDerializer xssStdDerializer = new XssStdDerializer(String.class);
        xssStdDerializer.setXssIgnoreList(xssIgnoreList);
        module.addDeserializer(String.class, xssStdDerializer);
        
        DateTimeFormatter dateF = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        module.addSerializer(LocalDate.class, new LocalDateSerializer(dateF));
        module.addDeserializer(LocalDate.class, new LocalDateDeserializer(dateF));
        
        DateTimeFormatter dateTimeF = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        module.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(dateTimeF));
        module.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(dateTimeF));
        
        objectMapper.registerModule(module);
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT);
        
        return objectMapper;
    }
	
}
